package com.gcloud.login;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;

import com.gcloud.dashboard.DashboardDesign;
import com.gcloud.librerias.DatabaseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gcloud.librerias.UserFunctions;
import com.gcloud.persistance.SQLiteHandler;
import com.utils.Constants;
import com.utils.GCloudUtil;
import com.utils.Message;
import com.example.gcode.*;
import com.example.gcode.R.drawable;

public class Login extends Activity {
	Button btnLogin;
	Button btnLinkToRegister;
	EditText inputEmail;
	EditText inputPassword;
	TextView loginErrorMsg;

	// JSON Response node names
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";
	private static String KEY_ERROR_MSG = "error_msg";
	private static String KEY_UID = "uid";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_CREATED_AT = "created_at";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		if (getKeys()) {
			redirectToDashBoard();
		}

		// Importing all assets like buttons, text fields
		inputEmail = (EditText) findViewById(R.id.sEmail);
		inputPassword = (EditText) findViewById(R.id.sPassword);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLinkToRegister = (Button) findViewById(R.id.link_to_register);
		// loginErrorMsg = (TextView) findViewById(R.id.login_error);

		// Login button Click Event
		btnLogin.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				String email = inputEmail.getText().toString();
				String password = inputPassword.getText().toString();
				if(!GCloudUtil.isEmpty(email)){
					showToast(GCloudUtil.Message(Message.FIELD_EMPTY, new String[]{"email"}));
					return;
				}
				if(!GCloudUtil.isEmpty(password)){
					showToast(GCloudUtil.Message(Message.FIELD_EMPTY, new String[]{"password"}));
					return;
				}
				LoginProcess loginProcess = new LoginProcess();
				loginProcess.execute(new String[] { email, password });
			}
		});

		// Link to Register Screen
		btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				// Intent intentnew = new Intent(Login.this,
				// GoogleDriveSyncronized.class);
				// startActivity(intentnew);
				// finish();

				// Intent DashboardDes = new Intent(getApplicationContext(),
				// DashboardDesign.class);
				// DashboardDes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				// startActivity(DashboardDes);
				// finish();

				Intent i = new Intent(getApplicationContext(), Registro.class);
				startActivity(i);
				finish();
			}
		});
	}

	public void redirectToDashBoard() {
		Intent DashboardDes = new Intent(getApplicationContext(),
				DashboardDesign.class);
		DashboardDes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(DashboardDes);
		finish();
	}

	public boolean getKeys() {
		SharedPreferences prefs = getSharedPreferences(
				Constants.gBoxSharedProperties, 0);
		String key = prefs.getString(Constants.trueAnswer,
				Constants.falseAnswer);
		return key != null && key.equals(Constants.trueAnswer);

	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 
	 */

	private ProgressDialog pDialog;

	class LoginProcess extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Login.this);
			pDialog.setMessage(Message.REGISTERING);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... args) {
			UserFunctions userFunction = new UserFunctions();
			Log.d("Button", "Login");
			// SQLiteHandler sqlite=new SQLiteHandler(Login.this,
			// Constants.GCLOUD, null, Constants.DB_VERSION);
			//
			// sqlite.insertFile("aaabbb"+Calendar.getInstance().getTimeInMillis(),
			// "meinefile"+email, "a file from a box",
			// "text/text", "1", email, true,
			// 1024, 1, (password!=null&&!password.isEmpty()));

			JSONObject json = userFunction.loginUser(args[0], args[1]);

			// check for login response
			try {
				if (json == null) {
					showToast("We have problems with you internet connecttion, please check it.");
					return "false";
				}
				if (json.getString(KEY_SUCCESS) != null) {
					// loginErrorMsg.setText("");
					Log.i("Logincpro: ", "keySuccess");
					String res = json.getString(KEY_SUCCESS);
					if (Integer.parseInt(res) == 1) {
						Log.i("inside success: ", "parseint=1");
						// user successfully logged in
						// Store user details in SQLite Database
						DatabaseHandler db = new DatabaseHandler(
								getApplicationContext());
						JSONObject json_user = json.getJSONObject("user");
						//
						// // Clear all previous data in database
						userFunction.logoutUser(getApplicationContext());
						// db.addUser("test", "test", "test", "test");
						db.addUser(json_user.getString(KEY_NAME),
								json_user.getString(KEY_EMAIL),
								json.getString(KEY_UID),
								json_user.getString(KEY_CREATED_AT));
						//
						// Launch Dashboard Screen

					} else {
						// Error in login
						loginErrorMsg.setText("Incorrect username/password");
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return "false";

		}

		String globalMPath = "";

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();

			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */

				}
			});

			Intent logValid = new Intent(getApplicationContext(),
					LoginValidator.class);

			// Close all views before launching Dashboard
			logValid.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(logValid);

			// Close Login Screen
			finish();

		}

	}

}